package org.dream.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;

import org.dream.ui.chart.impl.KChart;
import org.dream.ui.listener.KChartKeyListener;
import org.dream.ui.listener.MainKeyListener;

/**
 * 主界面
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class MainFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	// 下面两行是取得屏幕的高度和宽度
	private static final String TITLE = "关攀攀股票辅助系统";

	private Component centerPanel = null;
	private static MainFrame mainFrame = null;
	private JLabel statusLable = new JLabel("这里是状态栏");

	private MainFrame() {
		setTitle(TITLE);
		// this.setUndecorated(true);//去标题栏
		this.setSizeByScreen(); // 根据屏幕大小设计窗口大小
		this.setJMenuBar(MenuBuilder.getMenuBar());
		// this.setCenterPanel(new KChart("600028", "2011/05/18",
		// "2011/05/21"));
		this.setCenterPanel(StockTablePanel.getJTabbedPane());
		// 如果不获得焦点会使内组件接收鼠标滚动事件失效和键盘事件冲突

		this.setStateBar(); // 设置状态栏
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		this.addKeyListener(new MainKeyListener());
		
	}

	public static MainFrame getInstanse() {
		if (null == mainFrame) {
			throw new RuntimeException("mainframe is null");
		}
		return mainFrame;
	}

	public static synchronized void initialInstanse() {
		if (null == mainFrame) {
			mainFrame = new MainFrame();
		}
	}

	/**
	 * 设置状态栏
	 */
	private void setStateBar() {
		JToolBar toolBar = new JToolBar();

		toolBar.add(statusLable);// 把标签加到工具栏上

		this.add(toolBar, BorderLayout.SOUTH);
	}

	public void setStateText(String text) {
		statusLable.setText(text);
	}

	/**
	 * /根据屏幕大小设计窗口大小
	 */
	private void setSizeByScreen() {
		Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration()); // 是指获得屏幕的边界
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		setSize((int) screen.getWidth(), (int) screen.getHeight() - insets.bottom);
	}

	/**
	 * 设置中间面板
	 */
	public void setCenterPanel(Component panel) {
		if (null != this.centerPanel) {
			this.remove(this.centerPanel);
		}
		this.add(panel, BorderLayout.CENTER);
		this.setVisible(true);
		this.centerPanel = panel;
		if (panel instanceof KChart) {
			for (KeyListener keyListener : this.getKeyListeners()) {
				this.removeKeyListener(keyListener);
			}
			this.addKeyListener(new KChartKeyListener((KChart) panel));

		}
		this.requestFocus();

	}

	public Component getCenterPanel() {
		return this.centerPanel;
	}

}
